import db from "../db/db.js";

// 检查交易单号是否存在
function checkOrderNumberExists(orderNumber) {
    return new Promise((resolve, reject) => {
        db.query(
            `SELECT COUNT(*) AS count FROM consumptionRecord WHERE orderNumber = ?`,
            [orderNumber],
            (err, results) => {
                if (err) {
                    reject(err);
                    console.log("查询交易单号失败！");
                } else {
                    resolve(results[0].count > 0);
                }
            }
        );
    });
}

function insertConsumptionRecord(data,type) {
    let curCreateTime = new Date();
    return new Promise((resolve, reject) => {
        db.query(
            `
    INSERT INTO consumptionRecord SET 
    user = ?, source = ?, curCreateTime = ?, tradingTime = ?, tradingType = ?, counterParty = ?, tradeDescription = ?, receiptsAndExpenditure = ?, amount = ?, status = ?, orderNumber = ?, merchantNumber = ?, remark = ?, ignoreFlag = ?
    `,
            [
                "admin",
                type,
                curCreateTime,
                data.tradingTime,
                data.tradingType,
                data.counterParty,
                data.tradeDescription,
                data.receiptsAndExpenditure,
                data.amount,
                data.status,
                data.orderNumber.toString().trim(),
                data.merchantNumber,
                data.remark,
                0,
            ],
            (err, results) => {
                if (err) {
                    reject(err);
                    console.log("消费记录写入失败！");
                } else {
                    // console.log("消费记录写入成功！");
                }
            }
        );
    });
}

export default function csvToSQL(data, type) {
    let resData:any = [];
    // 微信处理
    if (type === "wechat") {
        data.forEach(element => {
            resData.push({
                tradingTime: element["交易时间"],
                tradingType: element["交易类型"],
                counterParty: element["交易对方"],
                tradeDescription: element["商品"],
                receiptsAndExpenditure: element["收/支"],
                amount: element["金额(元)"].split('¥')[1],
                status: element["当前状态"],
                orderNumber: element["交易单号"],
                merchantNumber: element["商户单号"],
                remake: element["备注"],
            });
        })
    }
    // 支付宝处理
    if (type === "alipay") {
        data.forEach(element => {
            resData.push({
                tradingTime: element["交易时间"],
                tradingType: element["交易分类"],
                counterParty: element["交易对方"],
                tradeDescription: element["商品说明"],
                receiptsAndExpenditure: element["收/支"],
                amount: element["金额"],
                status: element["交易状态"],
                orderNumber: element["交易订单号"],
                merchantNumber: element["商家订单号"],
                remake: element["备注"],
            })
        });
    }
    if (type === "custom") {
        data.forEach(element => {
            resData.push({
                tradingTime: element["交易时间"],
                tradingType: element["交易分类"],
                counterParty: element["交易对方"],
                tradeDescription: element["商品说明"],
                receiptsAndExpenditure: element["收/支"],
                amount: element["金额"],
                status: element["交易状态"],
                orderNumber: element["交易订单号"],
                merchantNumber: element["商家订单号"],
                remake: element["备注"],
            })
        });        
    }
    // resData.forEach(element => {
    //     dbDetail(element,type);
    // })
    // 遍历处理后的数据
    resData.forEach(async element => {
        try {
            const exists = await checkOrderNumberExists(element.orderNumber);
            if (!exists) {
                await insertConsumptionRecord(element, type);
            } else {
                console.log(`交易单号 ${element.orderNumber} 已存在，未插入新记录。`);
            }
        } catch (error) {
            console.log("处理过程中出现错误：", error);
        }
    });
}
